package com.itxiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itxiao.config.RedisKeyConfig;
import com.itxiao.dao.UserDao;
import com.itxiao.entity.User;
import com.itxiao.pojo.dto.UpdateUserDto;
import com.itxiao.pojo.vo.R;
import com.itxiao.service.UserService;
import com.itxiao.util.AliOssUtil;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2025-10-12 17:16:47
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Reference
    private UserDao userDao;
    @Resource
    private StringRedisTemplate template;

    @Override
    public R queryDetail(String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        return R.ok(sysUser);
    }

    @Override
    public R updateInfo(UpdateUserDto dto, String token) {
        User sysUser = JSON.parseObject(
                template.opsForValue().get(RedisKeyConfig.AUTH_LOGIN_TOKEN + token),
                User.class
        );
        if (sysUser == null) {
            return R.fail("解析令牌失败");
        }
        sysUser.setAvatar(dto.getAvatar());
        sysUser.setNickname(dto.getNickname());
        int i = userDao.updateById(sysUser);
        if (i <= 0) {
            return R.ok("插入失败");
        }
        return R.ok();
    }

    @Override
    public R uploadImg(MultipartFile file) {
        //1.验证
        if(!file.isEmpty()){
            //2.获取文件名
            String fn= AliOssUtil.rename(file.getOriginalFilename());
            try {
                if(AliOssUtil.upload(AliOssUtil.BUCKET,fn,file.getBytes())){
                    Calendar calendar=Calendar.getInstance();
                    calendar.add(Calendar.YEAR,3);
                    Date date=calendar.getTime();
                    String url=AliOssUtil.createUrl(AliOssUtil.BUCKET,fn,date);
                    return R.ok(url);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("未上传任何文件");
    }
}

